#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 16-10-22 下午8:36
# @Author  : ubuntu
# @Link    : xycfree@163.com
# @Version : 

import os
import time
import conf, db
import paramiko


class Remote(object):
	def __init__(self):
		pass

	# 获取所有host地址
	def get_hosts(self):
		query = 'SELECT ip FROM cmdb  '
		try:
			datas = db.db_select_all(query)  # 以元组形式返回((xx,),(xx,))
			if type(datas) is tuple:
				data = [data[0] for data in datas]
				result = {
					'code': 0000,
					'message': conf._code.get(0000, '查询成功'),
					'data': data
				}
			else:
				result = {
					'code': 2008,
					'message': conf._code.get(2008, '查询条件不符') + datas
				}

			return result
		except Exception, e:
			result = {
				'code': 2009,
				'message': str(e)
			}
			return result

	# 通过paramiko模块运行命令
	def run(self, ip, command):
		ssh = paramiko.SSHClient()  # paramiko 建立连接
		ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
		query = 'SELECT username, password, port FROM cmdb WHERE ip="{ip}"'.format(ip=ip)
		try:
			data = db.db_select_on(query)
			print data,type(data)
			if type(data) is tuple and len(data)>0:  # 查询成功返回元组
				username, password, port = data
				ssh.connect(hostname=ip, username=username, password=password, port=int(port))
				# if username != 'root':
				# 	buff = self.switch_root(root_pass, ssh, command)  # 普通用户切换至root
				# 	result = {
				# 		'code': 0000,
				# 		'message': buff
				# 	}
				# else:
				stdin, stdout, stderr = ssh.exec_command(command)
				serr = stderr.read()
				if serr:
					result = {
						'code': 2015,
						'message': conf._code.get(2015, '执行远程命令失败'),
						'data': {
							'content': serr
						}
					}
				else:
					result = {
						'code': 0000,
						'message': conf._code.get(0000, '执行远程命令成功'),
						'data': {
							'content': stdout.read()
						}
					}
				ssh.close()
				result['ip'] = ip
				return result
			else:
				result = {
					'code': 2009,
					'message': conf._code.get(2009, '数据库连接异常，请联系管理员')
				}
				result['ip'] = ip
				return result
		except Exception, e:
			result = {
				'code': 2009,
				'message': str(e)
			}
			result['ip'] = ip
			return result

	# 批量执行命令
	def runs(self, info, command):
		result = {}
		for hostname in info:
			host_ret = self.run(ip=hostname, command=command)
			result[hostname] = host_ret
		return result

	# 登录普通用户切换为root用户
	def switch_root(self, root_pass,ssh, command):
		ssh1 = ssh.invoke_shell() #建立子shell进程
		# time.sleep(0.1)
		ssh1.send('su - root \n')
		buff = ''
		while not buff.endswith('Password: '):
			resp = ssh1.recv(9999)
			buff += resp
		ssh1.send(root_pass)
		ssh1.send('\n')
		buff = ''
		while not buff.endswith('# '):
			resp = ssh1.recv(9999)
			buff += resp
		ssh1.send(command)  # 发送命令，回车执行
		ssh1.send('\n')
		buff = ''
		while not buff.endswith('# '):
			resp = ssh1.recv(9999)
			buff += resp
		ssh1.close()
		return buff


if __name__ == '__main__':
	r = Remote()
	# result = r.get_hosts()
	# print result['code'], result['message']
	# print result['data']

	res = r.run('192.168.40.128', 'mkdir /home/wang/uploads') #123.56.189.127
	print res
	print res['message'],res['data']['content']
	# print res['ip'], res['code'], res['message'],res['data']
	# res = r.switch_root('srv','LOcE1-aWbfk2FNU=')
